﻿using UnityEditor;
using UnityEngine;

namespace XFGameFramework.Localization
{
    public class ListenerFileEvent : UnityEditor.AssetModificationProcessor
    { 
        public static AssetDeleteResult OnWillDeleteAsset(string assetPath, RemoveAssetOptions option)
        { 
            MultiLanguageConfigs multiLanguageConfig = AssetDatabase.LoadAssetAtPath<MultiLanguageConfigs>(assetPath);

            if (multiLanguageConfig != null)
            {
                for (int i = 0; i < multiLanguageConfig.Languages.Count; i++)
                {
                    if (multiLanguageConfig.Languages[i] == null) continue;
                    AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(multiLanguageConfig.Languages[i]));
                }

                string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(multiLanguageConfig));
                string dir = string.Format("Assets/Extensions/Localization/{0}", guid);
                AssetDatabase.DeleteAsset(dir);

                if (!Application.isPlaying) 
                {
                    LocalizationManager.Configs.Clear();    
                }

            }

            return AssetDeleteResult.DidNotDelete; 
        }


        [UnityEditor.Callbacks.OnOpenAsset(0)]
        private static bool OnOpenAsset(int insId, int line)
        {
            MultiLanguageConfigs obj = EditorUtility.InstanceIDToObject(insId) as MultiLanguageConfigs;
            if (obj != null)
            {
                MultiLanguageConfigsInspector.OpenLocalizationConfigs(obj);
            }
            return obj != null;
        }

    }
}

